import { DEFAULT_PROTABLE_OPTIONS } from '@/constants';
import {
  DeleteOutlined,
  EditOutlined,
  PlusCircleOutlined,
} from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Popconfirm, Tag, Tooltip } from 'antd';
import { useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';

import { getMaterialListPaginated, removeMaterial } from '@/services/materialManageApi';
import MaterialEditDrawer from './components/EditDrawer';

/**
 * 库存管理
 */
export default function MaterialManagePage() {
  const [openEditDrawer, setOpenEditDrawer] = useState(false);
  const [editRecord, setEditRecord] = useState<MATERIAL.MaterialModel | null>(null);
  const tableActionRef = useRef<ActionType>();
  const requestRemove = useRequest(removeMaterial, {
    manual: true, // 关闭自动请求
    onSuccess: () => {
      // 重新加载表格
      tableActionRef.current?.reload();
    },
  });

  const columns = useMemo<ProColumns<MATERIAL.MaterialModel>[]>(
    () => [
      {
        dataIndex: 'materialName',
        title: '物资名称',
        width: 150,
      },
      {
        dataIndex: 'specification',
        title: '规格型号',
        width: 120,
        hideInSearch: true,
      },
      {
        dataIndex: 'quantity',
        title: '库存数量',
        width: 100,
        hideInSearch: true,
        render: (_, record) => {
          return (
            <span>
              {record.quantity} {record.unit}
            </span>
          );
        },
      },
      {
        dataIndex: 'minQuantity',
        title: '最低库存',
        width: 100,
        hideInSearch: true,
        render: (_, record) => {
          return (
            <span>
              {record.minQuantity} {record.unit}
            </span>
          );
        },
      },
      {
        dataIndex: 'locationPath',
        title: '存放位置',
        width: 150,
        hideInSearch: true,
      },
      {
        dataIndex: 'responsiblePerson',
        title: '负责人',
        width: 100,
      },
      {
        dataIndex: 'status',
        title: '状态',
        width: 100,
        valueEnum: {
          '正常': { text: '正常', status: 'Success' },
          '不足': { text: '不足', status: 'Warning' },
          '待补充': { text: '待补充', status: 'Error' },
          '已报废': { text: '已报废', status: 'Default' },
        },
        render: (_, record) => {
          // 根据库存数量与最低库存比较自动判断状态
          let statusText = '正常';
          let statusColor = 'success';
          
          if (record.status === '已报废') {
            statusText = '已报废';
            statusColor = 'default';
          } else if (record.quantity === 0) {
            statusText = '待补充';
            statusColor = 'error';
          } else if (record.quantity <= record.minQuantity) {
            statusText = '不足';
            statusColor = 'warning';
          }
          
          return <Tag color={statusColor}>{statusText}</Tag>;
        },
      },
      {
        dataIndex: 'createTime',
        title: '创建时间',
        width: 180,
        hideInSearch: true,
        render: (_, record) => {
          return record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '-';
        },
      },
      {
        dataIndex: 'createTime',
        title: '创建时间',
        hideInTable: true,
        valueType: 'dateRange',
        search: {
          transform: (value: any) => {
            return {
              startDate: value[0] ? dayjs(value[0]).format('YYYY-MM-DD') : undefined,
              endDate: value[1] ? dayjs(value[1]).format('YYYY-MM-DD') : undefined,
            };
          },
        },
      },
      {
        title: '操作',
        valueType: 'option',
        width: 120,
        render: (_, record) => [
          <Tooltip key="edit" title="编辑">
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => {
                setEditRecord(record);
                setOpenEditDrawer(true);
              }}
            />
          </Tooltip>,
          <Tooltip key="delete" title="删除">
            <Popconfirm
              title="确定要删除该物资吗？"
              onConfirm={() => {
                requestRemove.run(record.id);
              }}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                loading={requestRemove.loading}
              />
            </Popconfirm>
          </Tooltip>,
        ],
      },
    ],
    [requestRemove],
  );

  return (
    <PageContainer>
      <ProTable<MATERIAL.MaterialModel>
        actionRef={tableActionRef}
        columns={columns}
        request={async (params) => {
          // 转换参数
          const { current, pageSize, ...rest } = params;
          // 调用API
          const res = await getMaterialListPaginated({
            current,
            pageSize,
            ...rest,
          });
          return {
            data: res.data.records,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
        rowKey="id"
        {...DEFAULT_PROTABLE_OPTIONS}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusCircleOutlined />}
            onClick={() => {
              setEditRecord(null);
              setOpenEditDrawer(true);
            }}
          >
            新增
          </Button>,
        ]}
      />

      {/* 编辑抽屉 */}
      <MaterialEditDrawer
        open={openEditDrawer}
        record={editRecord}
        onFinish={() => {
          setOpenEditDrawer(false);
          setEditRecord(null);
          // 刷新表格
          tableActionRef.current?.reload();
        }}
        onCancel={() => {
          setOpenEditDrawer(false);
          setEditRecord(null);
        }}
      />
    </PageContainer>
  );
}